<?php

namespace app\command\task;
use app\api\service\alipay\Payment;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
use app\common\model\CashOutLog;
use app\common\model\store\Setting;
use app\common\model\User;
use app\store\model\user\BalanceLog;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;

class AiCheckCash
{
    public function handle()
    {
        Log::channel('command')->write('开始自动审核提现======');
        $this->run();
        Log::channel('command')->write('结束自动审核提现======');
    }

    public function run(){
        //测试环境不能提现
        $setting  = Setting::where('key','=','cash_ai_check')->find();
        if(!Config::get('app.debug') && $setting->status == 1){
            $this->aiCheckCash();
        }
    }

    //自动审核提现
    public function aiCheckCash(): bool
    {
        Db::startTrans();
        try {
            $condition = [
                ['process','=',2],
                ['status','=',0]
            ];
            $list = (new CashOutLog())->where($condition)->select();
            if(!$list->isEmpty()){
                foreach ($list as $cash_log){
                    $userModel = User::where(['user_id' => $cash_log->user_id,'is_delete' => 0])->find();
                    //用户已被删除，无需审核
                    if(!$userModel) continue;
                    //记录为改版之前记录，无需审核
                    if($userModel->withdrawal_price <= 0) continue;
                    $postData = [
                        'order_no' => $cash_log->order_no,
                        'amount' => $cash_log->amount,
                        'identity' => $cash_log->identity,
                        'name' => $cash_log->name,
                    ];
                    $aliPayment =  app(Payment::class);
                    $res = $aliPayment->transfer($postData);
                    Log::channel('command')->info('AI审核调用支付宝详情：'.json_encode($res,JSON_UNESCAPED_UNICODE));
                    if(isset($res['status'])  && $res['status'] == 'SUCCESS' ) {
                        //提现成功
                        $cash_log->trans_no = $res['pay_fund_order_id']; //流水号
                        $cash_log->reason = $res['msg'];
                        $cash_log->status = 1;
                        // 新增余额变动记录
                        BalanceLog::add(SceneEnum::CASHOUT, [
                            'user_id' => $cash_log->user_id,
                            'money' => $cash_log->amount * -1,
                        ], ['order_no' => $cash_log->order_no]);
                        $userModel->withdrawal_price = Db::raw('withdrawal_price-' . $cash_log->amount);
                    }else{
                        //提现失败
                        $cash_log->status = -1;
                        $cash_log->reason =  $res['sub_msg'] ?? '';
                        $userModel->withdrawal_price = Db::raw('withdrawal_price-' . $cash_log->amount);
                        $userModel->balance = Db::raw('balance+' . $cash_log->amount);
                    }
                    $cash_log->remark = 'AI自动审核';
                    $cash_log->save();
                    $userModel->save();
                }
            }
            Db::commit();
            return true;
        }catch (\Exception $exception){
            Db::rollBack();
            Log::channel('command')->info($exception->getMessage());
            return false;
        }
    }

}